<?php
namespace qiye\modules\ai\controllers;
use common\core\Controller;
use Yii;
use common\helps\Curl;

class DownLoadController extends Controller
{
    public $curl;
    public $redis;

    public function init()
    {
        $this->curl = new Curl();
        $this->redis = Yii::$app->redis;
    }

    //此处为语音或图片文件下载，根据API接口实现不同功能，js-sdk文档地址：http://work.weixin.qq.com/api/doc#10029
    //csdn 地址为：https://blog.csdn.net/qq_38997379/article/details/80832870


    //    语音下载
    public function actionIndex(){
        $corpId= 'ww*********';
    	if (Yii::$app->request->post()){
    		$data = Yii::$app->request->post();
    		$serverId = $data['serverId']; //此处为语音上传获取到的media_id
            $access_token = $this->getAiAccessToken($corpId);
    		$voice_url = 'https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token='.$access_token.'&media_id='.$serverId;

    		//此处路径，需要根据自己需求定
            $dir = "/upload/voice/";   //保存路径，相对当前文件的路径
            $outPath = "/upload/voice/";  //输出路径，
            if (!\common\helps\Tools::createFolder($dir)) {
                $this->result['info'] = '创建文件夹失败';
                $this->ajaxReturn($this->result);
            }

            //上面创建文件夹可以用
            /*if(!is_dir($dir)){
                mkdir($dir);
            }*/

            $filename = "wxupload_".time().rand(111,999).".amr"; //文件名称
            $this->downAndSaveFile($voice_url,$dir."/".$filename); //$outPath.$filename 为语音文件的目录
            return $outPath.$filename;  //文件已保存到本地文件夹中，快去看看吧
    	}
    }
    //根据URL地址，下载文件
    public function downAndSaveFile($url,$savePath){
        ob_start();
        readfile($url);
        $img  = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp = fopen($savePath, 'a');
        fwrite($fp, $img);
        fclose($fp);
    }

    //获取aiaccess_token
    public function getAiAccessToken($qiye_id,$cropid){
        if(!$this->redis->get('ai_access_token')){
            //企业corpid 和该应用secret
            $access_token_url= 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$cropid.'&corpsecret=afdasdfasfasdfas';
            $request = $this->curl->request($access_token_url,[],'get');
            $request = json_decode($request);
            $this->redis->set($qiye_id.':ai_access_token',$request->access_token);
            $this->redis->expire($qiye_id.':ai_access_token',7000);
        }

        return $this->redis->get($qiye_id.":ai_access_token");
    }

   
}